package com.yiyi.word_test.service.impl;

import com.yiyi.word_test.service.UserService;
import com.yiyi.word_test.util.OpenIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RestTemplate restTemplate;

    // 通过微信官方接口获取用户唯一标识符openid
    public String getOpenId(String code) {
        // 通过接口获取openid
        String url = OpenIdUtil.appendUrl(code).toString();
        ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
        // 将获取回来的数据作字符串处理，后切割字符串，获得需要的返回数据
        String[] result = responseEntity.getBody().toString().split(":");
        // 若有错误，返回错误信息
        if (result[0].equals("{\"errcode\"")) {
            return null;
        } else {
            // 否则返回openid
            return result[2].substring(1, result[2].length() - 2);
        }
    }
}
